/*
   Copyright (C) 2007 Yen-Ju Chen <yjchenx gmail>

   This application is free software; you can redistribute it and/or 
   modify it under the terms of the MIT license. See COPYING.

*/

#import "HRObject.h"

NSString *kHiNetRadioURLProperty = @"kHiNetRadioURLProperty";
NSString *kHiNetRadioMMSProperty = @"kHiNetRadioMMSProperty";
NSString *kHiNetRadioNameProperty = @"kHiNetRadioNameProperty";

@implementation HRObject
+ (void) initialize
{
	/* GNU ObjC runtime does not call +initialize in super.
	   So we have to include all properties from OKObject */
    NSDictionary *pt = [OKObject propertiesAndTypes];
    [HRObject addPropertiesAndTypes: pt];
    pt = [[NSDictionary alloc] initWithObjectsAndKeys:
        [NSNumber numberWithInt: kOKStringProperty],
            kHiNetRadioURLProperty,
        [NSNumber numberWithInt: kOKStringProperty],
			kHiNetRadioMMSProperty,
        [NSNumber numberWithInt: kOKStringProperty],
			kHiNetRadioNameProperty,
        nil];
    [HRObject addPropertiesAndTypes: pt];
    DESTROY(pt);
}

- (id) initWithName: (NSString *) name url: (NSString *) url;
{
	self = [self init];
	[self setValue: name forProperty: kHiNetRadioNameProperty];
	[self setValue: url forProperty: kHiNetRadioURLProperty];
	return self;
}

- (id) valueForProperty: (NSString *) property
{
	if ([property isEqualToString: kHiNetRadioMMSProperty])
	{
NSLog(@"here");
		/* We always try to get mms in case it fails previous */
		NSBundle *bundle = [NSBundle bundleForClass: [self class]];
		NSString *path = [bundle pathForResource: @"mms" ofType: @"rb"];
		NSArray *args = [NSArray arrayWithObjects: 
			path, 
			[self valueForProperty: kHiNetRadioURLProperty],
			nil];
		NSTask *task = AUTORELEASE([[NSTask alloc] init]);
		NSPipe *pipe = [NSPipe pipe];
		NSFileHandle *handle = [pipe fileHandleForReading];
		[task setLaunchPath: @"/usr/bin/ruby"];
		[task setArguments: args];
		[task setStandardOutput: pipe];
		[task launch];
		[task waitUntilExit];
		NSData *data = [handle readDataToEndOfFile];
		NSString *mms = AUTORELEASE([[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);
		[handle closeFile];
		if ([mms hasPrefix: @"mms"])
		{
			[self setValue: mms forProperty: kHiNetRadioMMSProperty];
			return mms;
		}
		else
		{
			return nil;
		}
	}
	return [super valueForProperty: property];
}

/* OKObject */
- (id) valueForKeyPath: (NSString *) keyPath
{
	if ([keyPath isEqualToString: kHiNetRadioMMSProperty])
		return nil;
	else if ([keyPath isEqualToString: qOKTextContent])
		return [self valueForProperty: kHiNetRadioNameProperty];
	return [super valueForKeyPath: keyPath];
}

- (id) valueForKey: (NSString *) key
{
	if ([key isEqualToString: kHiNetRadioMMSProperty])
		return nil;
	else if ([key isEqualToString: qOKTextContent])
		return [self valueForProperty: kHiNetRadioNameProperty];
	return [super valueForKey: key];
}

@end

